package com.yunshu.yunshuapp.banner;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.utils.YSUtils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhouwenjie on 2016/12/21.
 */
public class ScrollBanner extends RelativeLayout{

    public String[] adList;
    private ImageView[] imageViews;
    private View[] dots;
    private LinearLayout dotsContainer;
    private View contentView;
    private ViewPager adViewPager;
    private int currentItem = 0; // 当前图片的索引号

    private ScheduledExecutorService scheduledExecutorService;

    // 异步加载图片
    private ImageLoader mImageLoader;

    public OnClickListener bannerClickListener;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            adViewPager.setCurrentItem(currentItem);
        }

        ;
    };

    public ScrollBanner(Context context) {
        super(context);
        initView(context);
    }

    public ScrollBanner(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public ScrollBanner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs,defStyleAttr);
        initView(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ScrollBanner(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs,defStyleAttr,defStyleRes);
        initView(context);
    }

    private void initView(Context context) {
        if (isInEditMode()) { return; }

        this.contentView = View.inflate(context, R.layout.banner,this);
        this.contentView.setBackgroundColor( YSUtils.getColor( R.color.background_gray,context));
        adViewPager = (ViewPager) findViewById(R.id.vp);
        adViewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
        // 设置一个监听器，当ViewPager中的页面改变时调用
        MyPageChangeListener listener = new MyPageChangeListener();
        adViewPager.addOnAdapterChangeListener(listener);
        adViewPager.addOnPageChangeListener(listener);
        dotsContainer = (LinearLayout)findViewById(R.id.dotsContainer);
        // 使用ImageLoader之前初始化
        YSUtils.initImageLoader(this.getContext());

        // 获取图片加载实例
        mImageLoader = ImageLoader.getInstance();
    }

    public void setImages(String[] imgUrls){
        adList = imgUrls;
        imageViews = new ImageView[imgUrls.length];
        dots = new View[imgUrls.length];

        for (int i = 0 ; i<imgUrls.length ; i ++ ) {
            View dot=new View(this.getContext());
            dot.setBackgroundResource(
                    R.drawable.circleshape);
            dots[i] = dot;

            LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(16,16);
            params.leftMargin=10;
            dot.setLayoutParams(params);
            dot.setEnabled(false);

            dotsContainer.addView(dot);
        }
        addDynamicView();
        adViewPager.getAdapter().notifyDataSetChanged();
        startAd();
    }

    private void addDynamicView() {
        // 动态添加图片和下面指示的圆点
        // 初始化图片资源
        for (int i = 0; i < adList.length; i++) {
            ImageView imageView = new ImageView(this.getContext());
            // 异步加载图片
            mImageLoader.displayImage(adList[i], imageView);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP
            );
            imageViews[i] = imageView;
        }
    }

    private void startAd() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        // 当Activity显示出来后，每两秒切换一次图片显示
        scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2,
                TimeUnit.SECONDS);
    }



    public void stop() {
        if (scheduledExecutorService != null )
           scheduledExecutorService.shutdown();
    }

    public int indexOfView(View view) {
        for (int i = 0; i < this.imageViews.length; i++) {
            View iView = this.imageViews[i];
            if (iView == view) return i;
        }
        return -1;
    }

    private class ScrollTask implements Runnable {

        @Override
        public void run() {
            synchronized (adViewPager) {
                currentItem = (currentItem + 1) % imageViews.length;
                handler.obtainMessage().sendToTarget();
            }
        }
    }

    private class MyPageChangeListener implements ViewPager.OnAdapterChangeListener,ViewPager.OnPageChangeListener {

        private int oldPosition = 0;


        public void onPageScrollStateChanged(int arg0) {
            int i = 0;
        }

        public void onPageScrolled(int arg0, float arg1, int arg2) {
            int i = 0;

        }

        public void onPageSelected(int position) {

            dots[oldPosition].setBackgroundResource(R.drawable.dot_normal);
            dots[position].setBackgroundResource(R.drawable.dot_focused);
            oldPosition = position;
        }

        @Override
        public void onAdapterChanged(@NonNull ViewPager viewPager, @Nullable PagerAdapter oldAdapter, @Nullable PagerAdapter newAdapter) {

        }
    }

    private class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (adList == null) return 0;
            return adList.length;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView iv = imageViews[position];
            ((ViewPager) container).addView(iv);

            // 在这个方法里面设置图片的点击事件
            iv.setOnClickListener( bannerClickListener );
            return iv;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

            ((ViewGroup) container).removeView((View) object);

            object=null;
        }
    }
}
